#include <myheader.h>

/*Usage:achieve one quest one answer */
int main(int argc, char *argv[])
{
    char *ip = "192.168.112.129";
    char *port = "8080";
    //create a socket endpoint
    int socket_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    ERROR_CHECK(socket_fd,-1,"socket");

    //create a socket_addr struct
    struct sockaddr_in sockaddr_in_struct;
    sockaddr_in_struct.sin_family = AF_INET;
    sockaddr_in_struct.sin_port = htons(atoi(port));
    sockaddr_in_struct.sin_addr.s_addr = inet_addr(ip);

    //socket reuse to solve the problem that after the server disconnecting,
    //the client cant reconnect the server immediately  
    int optval = 1;
    int ret = setsockopt(socket_fd,SOL_SOCKET,SO_REUSEADDR,&optval,
                         sizeof(optval));
    ERROR_CHECK(ret,-1,"setsockopt");

    //bind
    ret = bind(socket_fd,(struct sockaddr*)&sockaddr_in_struct,
                    sizeof(sockaddr_in_struct));
    ERROR_CHECK(ret,-1,"bind");

    //listen
    ret = listen(socket_fd,10);
    ERROR_CHECK(ret,-1,"listen");

    //accept
    struct sockaddr sockaddr_info;
    socklen_t socklen = sizeof(sockaddr_info);
    int net_fd = accept(socket_fd,&sockaddr_info,&socklen);
    ERROR_CHECK(net_fd,-1,"accept");

    //recv
    char buf[60] = {0};
    fd_set select_set;
    while(1){
        //fd_set
        FD_ZERO(&select_set);
        FD_SET(STDIN_FILENO,&select_set);
        FD_SET(net_fd,&select_set);
        int ret = select(net_fd + 1, &select_set,NULL,NULL,NULL);
        ERROR_CHECK(ret,-1,"select");

        //selsct
        if(FD_ISSET(STDIN_FILENO,&select_set)){
            //send
            memset(buf,0,sizeof(buf));
            int read_cnt = read(STDIN_FILENO,buf,sizeof(buf));
            if(read_cnt == 0){
                printf("disconnection\n");
                break;
            }
            ERROR_CHECK(read_cnt,-1,"read");

            int send_cnt = send(net_fd,buf,sizeof(buf),0);
            ERROR_CHECK(send_cnt,-1,"send");

        }else if(FD_ISSET(net_fd,&select_set)){
            //recv
            memset(buf,0,sizeof(buf));
            int rev_cnt = recv(net_fd,buf,sizeof(buf),0);
            ERROR_CHECK(rev_cnt,-1,"recv");
            if(rev_cnt == 0){
                printf("the other side disconnection\n");
                break;
            }
            printf("%s",buf);
        }

    }
    close(net_fd);
    close(socket_fd);
    return 0;

}

